﻿/// <reference path="jquery-1.7.1.min.js"/>

function SubmitForm() {

    $('#result').show();

    $.ajax({
        type: "POST",
        url: "/print_orders.aspx/GetOrders",
        data: JSON.stringify({ count: $('#orderCount').val() }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            PrintOrders(msg.d);
        },
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }
    });
}

function PrintOrders(orders) {

    // sending the first print without any interval
    SendPrint(orders[0], 0, orders.length);

    if (orders.length == 1) {
        PrintingFinished();
        return;
    }

    // sending rest of prints with specified delay seconds intervals
    var i = 1;
    var delay = $('#SelectPrintDelay').val();
    var interval = setInterval(
                function () {
                    SendPrint(orders[i], i, orders.length);
                    i++;
                    if (i >= orders.length)
                        clearInterval(interval);
                }, parseInt(delay));
}

function SendPrint(orderId, i, length) {

    $('#result').html('ارسال بارنامه ' + (i + 1) + ' از ' + length + ' به چاپگر ' + ' ... ');

    $.ajax({
        type: "POST",
        url: "/new_order.aspx/PrintOrder",
        data: JSON.stringify({ OrderId: orderId }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            if (i == length - 1) {
                PrintingFinished();
            }
        },
        error: function (xhr, status, error) {
            // Boil the ASP.NET AJAX error down to JSON.
            var err = eval("(" + xhr.responseText + ")");
            $('#result').html(err.Message);
        }
    });
}

function PrintingFinished() {
    $('#result').html('تمام بارنامه ها با موفقیت چاپ شدند');
}